package org.hhchat.leetcode.array;

import java.util.HashMap;
import java.util.Map;

public class code697 {
    static class Solution {
        public int findShortestSubArray(int[] nums) {
            Map<Integer,Integer> count = new HashMap<>();
            int max = Integer.MIN_VALUE;
            int shortLength = nums.length;
            for(int i=0;i<nums.length;i++){
                int c = count.getOrDefault(nums[i],0)+1;
                count.put(nums[i], c);
            }

            for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
                if( entry.getValue() >= max){
                    int start = getFirst(nums,entry.getKey());
                    int last = getLast(nums,entry.getKey());
                    if (max == entry.getValue()) {
                        shortLength = Math.min(shortLength, last+1-start);
                    }else{
                        shortLength = last + 1 - start;
                    }
                    max = entry.getValue();
                }
            }
            return shortLength;

        }

        public int getFirst(int []nums, int value){
            for(int i=0;i<nums.length;i++){
                if(nums[i]==value){
                    return i;
                }
            }
            return -1;
        }

        public int getLast(int []nums, int value){
            for(int i=nums.length-1;i>=0;i--){
                if(nums[i]==value){
                    return i;
                }
            }
            return -1;

        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1,2,2,3,1,4,2};
        System.out.println(solution.findShortestSubArray(nums));
    }
}
